package com.yinhai.uid.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author taojie
 * @Date: 2018/12/25 17:12
 * @Description:
 */

@Configuration
@EnableCaching
public class UidJedisConfiguration {

	@Bean
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	@ConfigurationProperties("uid.redis.jedis.pool")
	public JedisPoolConfig loadJedisPoolConfig(){
		return new JedisPoolConfig();
	}

	@Bean
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	@ConfigurationProperties("uid.redis.cluster")
	public RedisClusterConfiguration loadRedisClusterConfiguration(){
		return new UidRedisClusterConfiguration();
	}

	@Bean
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	public JedisConnectionFactory buildConnectionFactory(JedisPoolConfig poolConfig, RedisClusterConfiguration clusterConfig){
		return new JedisConnectionFactory(clusterConfig,poolConfig);
	}

	@Bean("redisTemplate")
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	public RedisTemplate buildRedisTemplate(JedisPoolConfig poolConfig, RedisClusterConfiguration clusterConfig){
		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(buildConnectionFactory(poolConfig,clusterConfig));
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
		return redisTemplate;
	}

	@Bean
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
		return redisTemplate.opsForValue();
	}

	@Bean
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
		return redisTemplate.opsForHash();
	}

}
